<?php

namespace App\Jobs;

use App\Models\CrowdMember;
use App\Models\Topic;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class JpushCreateTopic implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $topicId;
    private $content;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($topicId, $content)
    {
        $this->topicId  = $topicId;
        $this->content  = $content;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $alias = [];

        $topic = Topic::where('id', $this->topicId)->first();
        if($topic){
            $uid = $topic->uid;
            $crowdId = $topic->crowd_id;

            $crowdMember = CrowdMember::where('crowd_id', $crowdId)
                ->whereNull('deleted_at')
                ->where('user_id', '<>', $uid)
                ->get();

            foreach ($crowdMember as $cm){
                if(!in_array((string)$cm->user_id, $alias)) {
                    $alias[] = (string)$cm->user_id;
                }
            }
        }
        \Log::debug($alias);

        if(!empty($alias)) {
            $jpush = new \App\Libs\Jiguang\Jpush();
            $jpush->pushAliasToAllPlatform($alias, $this->content, [
                'type' => 'CircleDetail',
                'id' => $this->topicId,
            ]);
        }
    }
}
